/**
 * Created by tanbingqin on 2020/5/15.
 */
import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import errorMessage from 'share/errorMessage';
import { message, Button, Popconfirm, Icon, Form, Input, Switch, Row, Col, Radio, TimePicker, Divider, Modal, Alert } from 'antd';
const FormItem = Form.Item;
import consumerService from '../consumer.service'
import Priority from 'components/template/priority'
import Condition from 'components/condition';
const If = Condition.If;
import AdvancedTable from 'components/advanced-table'
const { SimpleTable } = AdvancedTable;
import moment from 'moment'
import ExportModal from 'components/template/export-modal/export-modal';
import QrCode from "qrcode.react";

class AlipayEditFrame extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      refreshLoading: false,
      record: {},
      userVisible: false,
      columns: [
        {
          title: messages('common.user.id')/*工号*/,
          dataIndex: 'employeeID',
          width: '20%'
        },
        {
          title: messages('supplier-1.key163')/*姓名*/,
          dataIndex: 'fullName',
          width: '20%'
        },
        {
          title: messages('supplier-1.key164')/*开通时间*/,
          dataIndex: 'createdDate',
          width: '40%',
          render: (value, record) => moment(value).format('YYYY-MM-DD HH:mm:ss')
        },
        {
          title: messages('supplier-1.key165')/*使用状态*/,
          dataIndex: 'statusDesc',
          width: '20%'
        }
      ],
      priorityValue: {}, //所属组织，启用公司控件value
      authUrl: '', //授权链接
    }
  }

  componentDidMount() {
    const { tenantInfo, record } = this.props;
    let priorityValue = {
      levelCode: 'TENANT',
      levelOrgId: tenantInfo.id,
      levelOrgName: tenantInfo.tenantName
    };
    if (record && record.companyCardConfigDistDTOList && record.companyCardConfigDistDTOList.length) {
      priorityValue.distribution = {companies: []};
      record.companyCardConfigDistDTOList.forEach(company => {
        priorityValue.distribution.companies.push({name: company.levelOrgName, id: company.levelOrgId});
      });
    }
    this.setState({priorityValue, record});
    this.getUrl();
  };

  //获取授权链接
  getUrl = () => {
    consumerService.getCardAuthUrl().then(res => {
      this.setState({authUrl: res.data && res.data.url});
    }).catch(e => {
      errorMessage(e.response);
    });
  };

  onCancel = () => {
    this.props.close();
  };

  handleSave = () => {
    const { form, close, type } = this.props;
    const { priorityValue, record } = this.state;
    if (priorityValue.distribution && !priorityValue.distribution.companies.length) {
      message.error(messages('supplier-1.key166')/*请选择启用公司*/);
      return false;
    }
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let supplierCode = '003';
        let params = {
          id: record ? record.id : undefined,
          status: values.enable ? 1001 : 1002,
          mappingId: record.mappingId,
          companyCardConfigDistDTOList: []
        };
        if (priorityValue.distribution) {
          priorityValue.distribution.companies.map(company => {
            params.companyCardConfigDistDTOList.push({levelOrgId: company.id});
          });
        }
        this.setState({loading: true});
        consumerService.updateCardConfig(supplierCode, params).then(res => {
          this.setState({loading: false});
          close(true);
        }).catch(err => {
          this.setState({loading: false});
          errorMessage(err.response);
        });
      }
    });
  };

  closeModal = () => {
    this.setState({userVisible: false});
  };

  service = (page, pageSize) => {
    return consumerService.getUserOpenList(page, pageSize);
  };

  handleChangePriority = (value) => {
    this.setState({priorityValue: value || {}});
  };

  handleLink = () => {
    let url = this.state.authUrl;
    if (window.ISIE9) {
      url = `#${url}`;
    }
    window.open(url);
  };

  handleRefresh = () => {
    let { record } = this.state;
    this.setState({refreshLoading: true});
    consumerService.getCardAuthStatus(record && record.id).then(res => {
      record.authStatus = res.data.authStatus;
      record.mappingId = res.data.mappingId;
      record.isHasRefresh = true;
      this.setState({refreshLoading: false, record});
    }).catch(e => {
      this.setState({refreshLoading: false});
    });
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { loading, userVisible, columns, priorityValue, authUrl, refreshLoading, record } = this.state;
    const { type, isBydEnv } = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16, offset: 1}
    };
    return (
      <div className="new-form">
        <Form>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('enable', {
              valuePropName: 'checked',
              initialValue: record ? record.status === 1001 : true
            })(
              <Switch />
            )}
          </FormItem>
          {priorityValue.levelCode && (
            <Priority
              top='TENANT'
              formItemLayout={formItemLayout}
              onChange={this.handleChangePriority}
              defaultValue={priorityValue}
              disabledTop
            />
          )}
          <Divider />
          <If value={!record || record.authStatus !== 1002}>
            <Alert
              style={{marginBottom: 16}}
              message={messages('supplier-1.key167')/*注意：请使用已签约花呗工作花的企业支付宝账号进行授权*/}
              type="info"
              showIcon
            />
            <FormItem {...formItemLayout} label={messages('supplier-1.key168')/*授权方式*/}>
              <Row type="flex" align="middle">
                <span style={{display: 'inline-block'}}>
                  <div style={{width: 140}}>
                    <div style={{width: 140, height: 140, padding: '25px 25px', border: '1px solid #CDD7EC', borderRadius: '4px'}}>
                      <QrCode
                        value={authUrl}
                        renderAs={"svg"}
                        fgColor={"#000000"}
                        size={90}
                      />
                    </div>
                    <div style={{textAlign: 'center', marginTop: 8}}>
                      {messages('supplier-1.key169')/*支付宝APP扫码授权*/}
                    </div>
                  </div>
                </span>
                <span style={{display: 'inline-block', margin: '0 20px'}}>
                  {messages('supplier-1.key170')/*或*/}
                </span>
                <span style={{display: 'inline-block'}}>
                  <div style={{width: 140}}>
                    <div
                      style={{
                        width: 140,
                        height: 140,
                        padding: '25px 25px',
                        border: '1px solid #CDD7EC',
                        borderRadius: '4px',
                        lineHeight: '90px',
                        color: '#0092da',
                        cursor: 'pointer',
                        textAlign: 'center'
                      }}
                      onClick={this.handleLink}
                    >
                      {messages('supplier-1.key171')/*授权链接*/}
                    </div>
                    <div style={{textAlign: 'center', marginTop: 8}}>
                      {messages('supplier-1.key172')/*浏览器登录链接授权*/}
                    </div>
                  </div>
                </span>
              </Row>
            </FormItem>
          </If>
          <If value={!record || record.authStatus !== 1002}>
            <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
              <If value={!record.isHasRefresh}>
                <div style={{color: '#4E5B71'}}>
                  {messages('supplier-1.key173')/*操作后，点击刷新查看授权结果*/}
                </div>
              </If>
              <If value={record.isHasRefresh}>
                <div style={{color: '#4E5B71'}}>
                  {messages('supplier-1.key174')/*未获取到授权，请确保已使用企业支付宝授权。*/}
                </div>
              </If>
              <Button type="primary" loading={refreshLoading} onClick={this.handleRefresh}>{messages('supplier-1.key175')/*立即刷新*/}</Button>
            </FormItem>
          </If>
          <If value={record && record.authStatus === 1002}>
            <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
              <div>
                {messages('supplier-1.key126')/*已授权*/}
                <span
                  style={{display: 'inline-block', marginLeft: 12, color: '#1464F0', cursor: 'pointer'}}
                  onClick={() => {this.setState({userVisible: true})}}
                >
                  {messages('supplier-1.key176')/*查看已开通员工*/}
                </span>
              </div>
            </FormItem>
          </If>
        </Form>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={loading}>{messages('common.ok')/*确定*/}</Button>
          <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
        </div>
        <Modal
          title={messages('supplier-1.key177')/*已开通员工*/}
          visible={userVisible}
          onCancel={this.closeModal}
          maskClosable={false}
          destroyOnClose={true}
          width={800}
          footer={[
            <Button key="save" onClick={this.closeModal}>{messages('common.back')/*返回*/}</Button>
          ]}
        >
          <div style={{height: '595px', margin: '-20px 0 -24px 0'}}>
            <SimpleTable
              columns={columns}
              searchForm={[]}
              service={this.service}
              rowKey="employeeID"
              onRef={ref => this.simpleTableRef = ref}
              tableName='user-alipay-list'
            >
              <div className="table-header-buttons" style={{position: 'relative'}}>
                <div style={{marginLeft: '-20px'}}>
                  <ExportModal
                    type={"btn"}
                    exportTitle={messages('supplier-1.key178')/*导出*/}
                    exportType="HUA_BEI_USER_MAPPING_EXPORT"
                    exportCommand={'HUA_BEI_USER_MAPPING_EXPORT'}
                  />
                </div>
              </div>
            </SimpleTable>
          </div>
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    isBydEnv: state.main.isBydEnv,
    tenantInfo: state.login.tenant,
  }
}

AlipayEditFrame.propTypes = {};

AlipayEditFrame.defaultProps = {};

const WrappedAlipayEditFrame = Form.create()(AlipayEditFrame);

export default connect(mapStateToProps)(WrappedAlipayEditFrame);
